package com.bicycle.rentalsystem.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import com.bicycle.rentalsystem.handler.ResultHandler;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类
 * 查找使用query，增加、删除、更改使用update
 * 不需要更改
 */
public class JdbcUtil {

    private static final DruidDataSource dataSource = new DruidDataSource();

    public static void initDataSource(Properties props){
        dataSource.configFromPropety(props);
    }
    public static void destroyDataSource(){
        dataSource.close();
    }

    public static <T> T query(String sql, ResultHandler<T> handler, Object...params) {

        try {
            Connection conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            if (params != null && params.length > 0){
                for (int i = 0;i< params.length;i++){
                    ps.setObject(i+1,params[i]);
                }
            }
            ResultSet rs = ps.executeQuery();
            T t = handler.handle(rs);
            rs.close();
            ps.close();
            conn.close();
            return  t;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int update(String sql, Object...params){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            int affectedRows = ps.executeUpdate();
            ps.close();
            conn.close();
            return  affectedRows;
        } catch (SQLException e){
            e.printStackTrace();
        }
        return -1;
    }
}
